/**
 * 游戏时间 API 客户端
 */

const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:4000";

export interface GameTimeState {
  gameDate: string;
  gameDateFormatted: string;
  speed: 1 | 2 | 5 | 10 | 20 | 50 | 100 | 200 | 500;
  status: "playing" | "paused";
  isTradingDay: boolean;
  isTradingHours: boolean;
  timeToNextMarketOpen: number;
  startDate: string;
  gameTimeElapsed: number;
  realTimeElapsed: number;
}

/**
 * 获取当前游戏时间状态
 */
export async function getGameTime(): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time`);
  if (!response.ok) {
    throw new Error("获取游戏时间失败");
  }
  return response.json();
}

/**
 * 设置游戏时间速度
 */
export async function setGameTimeSpeed(
  speed: 1 | 2 | 5 | 10 | 20 | 50 | 100 | 200 | 500,
): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/speed`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ speed }),
  });
  if (!response.ok) {
    throw new Error("设置时间速度失败");
  }
  return response.json();
}

/**
 * 暂停游戏时间
 */
export async function pauseGameTime(): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/pause`, {
    method: "POST",
  });
  if (!response.ok) {
    throw new Error("暂停游戏时间失败");
  }
  return response.json();
}

/**
 * 继续游戏时间
 */
export async function resumeGameTime(): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/resume`, {
    method: "POST",
  });
  if (!response.ok) {
    throw new Error("继续游戏时间失败");
  }
  return response.json();
}

/**
 * 切换暂停/继续状态
 */
export async function toggleGameTime(): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/toggle`, {
    method: "POST",
  });
  if (!response.ok) {
    throw new Error("切换游戏时间状态失败");
  }
  return response.json();
}

/**
 * 跳转到指定日期
 */
export async function jumpToDate(date: string): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/jump`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ date }),
  });
  if (!response.ok) {
    throw new Error("跳转日期失败");
  }
  return response.json();
}

/**
 * 跳过当前交易日，直接到下一个交易日开盘
 */
export async function skipToNextTradingDay(): Promise<GameTimeState> {
  const response = await fetch(`${API_BASE_URL}/api/game/time/skip-day`, {
    method: "POST",
  });
  if (!response.ok) {
    throw new Error("跳过交易日失败");
  }
  return response.json();
}




